package org.bozo.im.service.protocols.xmpp.stanza.task.sasl;

import java.util.ArrayList;

import org.bozo.im.service.Constants;
import org.bozo.im.service.protocols.xmpp.XMPPSession;
import org.bozo.im.service.protocols.xmpp.stanza.task.Task;
import org.bozo.im.service.protocols.xmpp.stanza.util.sasl.Mechanism;
import org.bozo.im.service.protocols.xmpp.stanza.util.sasl.Mechanisms;

import android.util.Log;

public class AuthTask extends Task {

	public AuthTask(String pId) {
		super(pId);
	}

	@Override
	public void doTask(XMPPSession pSession, StringBuilder pBuilder) throws Exception {
		
		// ---------------------------------------------------------------------------------------
		Log.d(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.stanza.task.sasl.AuthTask.doTask ---------- Starting the SASL negociation");
		// ---------------------------------------------------------------------------------------
		
		Mechanism lMechanism = null;
		ArrayList<?> lMechanisms = (ArrayList<?>)pSession.getConfiguration().getProperty("sasl-mechanisms");

		if (lMechanisms != null) {

			for (Object lObj : lMechanisms) {
				if (lObj instanceof String) {
					String lMechanismStr = (String)lObj;
					lMechanism = Mechanisms.getMechanism(lMechanismStr);

					if (lMechanism != null)
						break;
				}
			}
		}

		if (lMechanism != null) {
			// ---------------------------------------------------------------------------------------
			Log.d(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.stanza.task.sasl.AuthTask.doTask ---------- Will be using this SASL mechanism: " + lMechanism.getName());
			// ---------------------------------------------------------------------------------------

			pSession.getConfiguration().putProperty("sasl-mechanism", lMechanism);
			lMechanism.toAuthStanza(pSession, pBuilder);
			
		} else {
			// ---------------------------------------------------------------------------------------
			Log.d(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.stream.features.sasl.AuthTask.doTask ---------- Could not find a valid mechanism");
			// ---------------------------------------------------------------------------------------
		}
	}
}
